package cn.tworice.admin.web;

import cn.tworice.common.utils.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 快速上传文件
 * @author 二饭[tworice@sina.cn][2022/2/12 22:12]
 */
@RestController
@RequestMapping("editor")
@Slf4j
@CrossOrigin
public class EditorController {

    private static final String UPLOAD_PATH = "/static/upload/";

    @PostMapping("upload")
    public Map<String, Object> upload(MultipartFile editorFile, String url,HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        UploadUtil uploadUtil = new UploadUtil();
        String path=uploadUtil.uploadFile(editorFile);


        result.put("errno", 0);
        result.put("data", new String[]{url+path});
        return result;
    }

    /**
     * 配置wangEditor5的图片上传
     * @param editorFile
     * @param url
     * @param request
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author 二饭 [2022/5/21]
     **/
    @PostMapping("editorUpload")
    public Map<String, Object> upload5(MultipartFile editorFile,HttpServletRequest request) {
        String serverName = request.getServerName();
        String scheme = request.getScheme();
        String url=scheme+"://"+serverName+":"+request.getServerPort();

        System.out.println(url);

        Map<String, Object> result = new HashMap<>();
        UploadUtil uploadUtil = new UploadUtil();
        try{
            String path=uploadUtil.uploadFile(editorFile);
            Map<String, String> map = new HashMap<>();
            map.put("url", url +"/"+ path);
            result.put("errno", 0);
            result.put("data", map);
        }catch (Exception ex){
            result.put("errno", 1);
            result.put("message", "图片上传失败");
        }

        return result;
    }

}
